//
//  NSURL+Utility.m
//  Utility
//
//  Created by Robin on 7/16/16.
//  Copyright © 2016 Robin. All rights reserved.
//

#import "NSURL+Utility.h"

@implementation NSURL (Utility)
- (NSDictionary*)dictionaryFromQueryUsingEncoding:(NSStringEncoding)encoding {
    NSString * query = [self query];
    
    NSCharacterSet * delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"];
    NSMutableDictionary * pairs = [NSMutableDictionary dictionary];
    NSScanner* scanner = [[NSScanner alloc] initWithString:query];
    
    while (![scanner isAtEnd]) {
        NSString* pairString = nil;
        [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString];
        [scanner scanCharactersFromSet:delimiterSet intoString:NULL];
        NSArray* kvPair = [pairString componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString* key = [[kvPair objectAtIndex:0] stringByRemovingPercentEncoding];
            NSString* value = [[kvPair objectAtIndex:1] stringByRemovingPercentEncoding];
            [pairs setObject:value forKey:key];
        }
    }
    
    return [NSDictionary dictionaryWithDictionary:pairs];
}
@end
